package com.cit.service.impl;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.cit.service.ValidateService;
/**
 * 
 * @author Lang Yu(lang.yu@hp.com)
 * @time Mar 7, 2011 12:05:48 PM
 * @file ValidateServiceImpl.java
 * @package com.cit.service.impl
 * @version 1.0
 * @see
 * ValidateService's implementation class
 */
public class ValidateServiceImpl implements ValidateService{
	@Override
	public boolean validateRequired(Document inputDoc,
			Document validateDoc, StringBuilder errorMessage) {
		boolean result = true;
		// Get the field configuration xml files root element.
		Element root = validateDoc.getDocumentElement();
		// Get the soap body's content, it is xml format and here get the xml data's root element.
		Element inputRoot = inputDoc.getDocumentElement();
		// Parse the field configuration xml and check with field must be required, get the field rule from field configuration
		NodeList list = root.getElementsByTagName("field");
		for (int i = 0; i < list.getLength(); i++) {
			Node node = list.item(i);
			NamedNodeMap attrs = node.getAttributes();
			if (attrs != null && attrs.getLength() > 0) {
				// Get the required node's value, it told us that the field is required or not.
				Node attr = attrs.getNamedItem("required");
				if (attr != null) {
					boolean requried = Boolean
							.parseBoolean(attr.getNodeValue());
					if (requried) {
						String name = attrs.getNamedItem("name").getNodeValue();
						NodeList inputList = inputRoot.getElementsByTagName(name);
						// The field with required rule can't be found in request content
						if( inputList == null || inputList.getLength() == 0){
							errorMessage.append("'" + name + "' ");
							result = false;
							continue;
						}
						// The field with required rule is empty string in request content
						// Just as <requiredfield></requiredfield>
						if( inputList.getLength() == 1){
							Node validateNode = inputList.item(0);
							if( validateNode.getTextContent() == null || validateNode.getTextContent().trim().equals("")){
								errorMessage.append("'" + name + "' ");
								result = false;
								continue;
							}
						}
					}else{
						// Optional field and continue to the next loop
						continue;
					}
				}
			}
		}
		/**
		 * If there exist the errorMessage, the validation process failure, so at last format the error messages and send
		 * response message to the client.
		 */
		return result;
	}
	
}
